package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    private ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);  //是创建TCP服务端Socket的API
    }

    public void start() throws IOException {
        System.out.println("服务器启动!");

        //线程池方法
        ExecutorService pool = Executors.newCachedThreadPool();  //可以一直扩容

        //服务器一上来就处理客户端的请求
        while (true) {
            Socket clientSocket = serverSocket.accept();  //接听操作  (客户端没有来连接上来就阻塞等待))

            //多线程方法
            //代码该成多线程的形式,就不能通过try()的方式来关闭clientSocket
/*            Thread t = new Thread(() -> {
                try {
                    processConnection(clientSocket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
            t.start();*/

            //把任务添加到线程池中
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnection(clientSocket);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });

        }
    }

    //通过这个方法处理一个连接
    private void processConnection(Socket clientSocket) throws IOException {
        //1. 打印一个日志,告知说当前有客户端连接上了
        System.out.printf("[%s:%d] 客户端上线!\n", clientSocket.getInetAddress(), clientSocket.getPort());
        //2. 从socket 中获取到流对象,来进一步后续操作
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {

            //3. 搞一个循环,针对每个连接,客户端都可能会发来多个请求,服务器也需要多个响应了
            Scanner scanner = new Scanner(inputStream);
            while (true) {
                //3.1 读取请求并解析(Scanner读到"空白符"才会读取完毕)
                if (!scanner.hasNext()) {  //判断是否有键盘输入
                    //如果发现后续没有数据了,说明TCP的连接是已经断开了
                    System.out.printf("[%s:%d] 客户端下线!\n", clientSocket.getInetAddress(), clientSocket.getPort());
                    break;
                }
                //如果按照read的方式来读,读出来的是byte[],还需转成String;使用Scanner,直接读出来就是String
                String request = scanner.next();
                //3.2 根据请求计算响应
                String response = process(request);
                //3.3 把响应写回给客户端
                outputStream.write(response.getBytes(), 0, response.getBytes().length);
                //3.4 服务器打印日志
                System.out.printf("[%s:%d] req=%s, resp=%s\n", clientSocket.getInetAddress(), clientSocket.getPort(), request, response);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            clientSocket.close();
        }
    }

    //根据请求计算响应:由于是回显服务器,直接把请求作为响应返回回去
    private String process(String request) {
        return request + "爱你\n";  //给响应后面加上换行符,是客户端读取响应的时候,也有明确的分隔符
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();
    }
}
